package handlers

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"sort"
	"sync"

	"ai-collections/pkg/models"
	"ai-collections/pkg/services"

	"github.com/gin-gonic/gin"
)

type CollectionsData struct {
	UserInfo  models.DownstreamUserInfo
	Channels  map[string][]services.Channel
	Error     string
	ActiveTab string              // 添加激活的页签字段
	Config    models.SystemConfig // 添加系统配置字段
}

func CollectionsHandler(c *gin.Context) {
	// 初始化数据结构
	data := CollectionsData{
		Channels:  make(map[string][]services.Channel),
		ActiveTab: "Claude",          // 默认页签
		Config:    GetSystemConfig(), // 获取系统配置
	}

	// 读取保存的页签选择cookie
	activeTab, err := c.Cookie("ai_collections_active_tab")
	if err == nil && activeTab != "" {
		data.ActiveTab = activeTab
		log.Printf("Restored active tab '%s' from cookie", activeTab)
	}

	// 从请求头获取并解密用户信息
	encryptedHeader := c.GetHeader("X-User-Info")
	log.Printf("Encrypted header: %s", encryptedHeader)
	var userInfo *models.DownstreamUserInfo

	if encryptedHeader != "" {
		userInfo, err = models.DecryptUserInfo(encryptedHeader, encryptionKey)
		if err != nil {
			log.Printf("Error decrypting user info: %v", err)
			userInfo = models.GuestUserInfo()
		}
	} else {
		userInfo = models.GuestUserInfo()
	}
	data.UserInfo = *userInfo

	// 获取用户邮箱，如果是游客则为空字符串
	userEmail := ""
	if !userInfo.IsGuest {
		userEmail = userInfo.Email
	}

	// 记录用户访问日志
	log.Printf("User access: %s (Email: %s, Roles: %v)",
		userInfo.Username,
		userInfo.Email,
		userInfo.Roles)

	// 处理不同频道的数据
	var wg sync.WaitGroup
	var mu sync.Mutex
	errorCount := 0
	var errorMu sync.Mutex

	// 处理错误的工具函数
	handleError := func(err error, message string) {
		errorMu.Lock()
		errorCount++
		errorMu.Unlock()
		log.Printf("%s: %v", message, err)
	}

	// 获取Claude频道数据
	if data.Config.ShowClaude {
		wg.Add(1)
		go func() {
			defer wg.Done()

			claudeCarPage, err := services.GetCarPageByType(services.ChannelTypeClaudeMin, 1, 50, userEmail)
			if err != nil {
				handleError(err, "Error fetching claude channel data")
				return
			}

			// 处理每个car的状态
			channels := fetchChannelStatuses(services.ChannelTypeClaudeMin, claudeCarPage, &wg, &mu, &errorMu, &errorCount, userEmail)

			// 添加到结果中
			mu.Lock()
			data.Channels[services.ChannelTypeClaudeMin] = channels
			mu.Unlock()
		}()
	}

	// 获取Plus频道数据
	if data.Config.ShowPlus {
		wg.Add(1)
		go func() {
			defer wg.Done()

			plusCarPage, err := services.GetCarPageByType(services.ChannelTypePlus, 1, 50, userEmail)
			if err != nil {
				handleError(err, "Error fetching plus channel data")
				return
			}

			// 处理每个car的状态
			channels := fetchChannelStatuses(services.ChannelTypePlus, plusCarPage, &wg, &mu, &errorMu, &errorCount, userEmail)

			// 添加到结果中
			mu.Lock()
			data.Channels[services.ChannelTypePlus] = channels
			mu.Unlock()
		}()
	}

	// 获取指纹频道数据
	if data.Config.ShowFingerprint {
		wg.Add(1)
		go func() {
			defer wg.Done()

			fingerprintCarPage, err := services.GetCarPageByType(services.ChannelTypeFingerprint, 1, 50, userEmail)
			if err != nil {
				handleError(err, "Error fetching fingerprint channel data")
				return
			}

			// 处理每个car的状态
			channels := fetchChannelStatuses(services.ChannelTypeFingerprint, fingerprintCarPage, &wg, &mu, &errorMu, &errorCount, userEmail)

			// 添加到结果中
			mu.Lock()
			data.Channels[services.ChannelTypeFingerprint] = channels
			mu.Unlock()
		}()
	}

	// 等待所有goroutine完成
	wg.Wait()

	// 检查是否所有请求都失败了
	totalRequests := 0
	if data.Config.ShowClaude {
		totalRequests++
	}
	if data.Config.ShowPlus {
		totalRequests++
	}
	if data.Config.ShowFingerprint {
		totalRequests++
	}

	if totalRequests > 0 && errorCount >= totalRequests {
		data.Error = "无法获取频道信息，请稍后重试"
	} else if errorCount > 0 {
		data.Error = "部分数据加载失败，请刷新重试"
	}

	// 排序各频道的卡片，可用的排在前面
	for channelType, channels := range data.Channels {
		// 按状态排序：FREE > BUSY > ERROR > UNKNOWN
		sort.Slice(channels, func(i, j int) bool {
			// 定义状态的优先级
			getPriority := func(status string) int {
				switch status {
				case "FREE":
					return 0
				case "BUSY":
					return 1
				case "ERROR":
					return 2
				default:
					return 3
				}
			}

			// 比较两个卡片的状态优先级
			return getPriority(channels[i].Status) < getPriority(channels[j].Status)
		})

		// 更新排序后的结果
		data.Channels[channelType] = channels
	}

	// 构建模板路径
	tmplPath := GetTemplatePath("collections.html")

	// 解析模板
	tmpl, err := template.ParseFiles(tmplPath)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// 渲染模板
	if err := tmpl.Execute(c.Writer, data); err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}
}

// 辅助函数：获取频道状态
func fetchChannelStatuses(channelType string, carPage *services.CarPageResponse, wg *sync.WaitGroup, mu *sync.Mutex, errorMu *sync.Mutex, errorCount *int, userEmail string) []services.Channel {
	var channels []services.Channel
	var channelMu sync.Mutex
	var localWg sync.WaitGroup

	// 特殊处理指纹频道，直接使用API响应中的状态信息
	if channelType == services.ChannelTypeFingerprint {
		for _, car := range carPage.Data.List {
			// 为指纹频道创建默认的状态响应
			status := &services.EndpointResponse{
				Color:         "green",
				Label:         car.Label, // 使用API响应中的browserTargName作为Label
				LabelColor:    "green",
				Message:       "指纹浏览器可用",
				NamedLogo:     car.Name, // 使用API响应中的browserName作为NamedLogo
				SchemaVersion: 1,
			}

			// 根据状态调整显示
			if car.Status != 1 {
				status.Color = "red"
				status.LabelColor = "red"
				status.Message = "指纹浏览器不可用"
			}

			// 创建频道
			channel := services.Channel{
				ID:   car.CarID,
				Name: fmt.Sprintf("%s - %s", car.Label, car.Name), // 使用browserTargName和browserName作为显示名称
				Type: channelType,
				Status: func() string {
					if car.Status == 1 {
						return "FREE"
					} else {
						return "ERROR"
					}
				}(),
				StatusClass: func() string {
					if car.Status == 1 {
						return "idle"
					} else {
						return "error"
					}
				}(),
				Key:        car.CarID,
				RealStatus: status.Message,
				IdleStatus: status.Label,
			}

			channels = append(channels, channel)
		}
		return channels
	}

	// 其他频道保持原有处理逻辑
	for _, car := range carPage.Data.List {
		localWg.Add(1)
		go func(carInfo struct {
			CarID  string `json:"carID"`
			Label  string `json:"browserTargName"`
			Name   string `json:"browserName"`
			IsPlus int    `json:"isPlus"`
			Status int    `json:"status"`
		}) {
			defer localWg.Done()

			// 获取状态
			status, err := services.GetEndpointStatus(channelType, carInfo.CarID)
			if err != nil {
				errorMu.Lock()
				*errorCount++
				errorMu.Unlock()
				log.Printf("Error fetching status for car %s in %s channel: %v", carInfo.CarID, channelType, err)
				return
			}

			// 转换为Channel
			channel := services.ConvertToChannel(channelType, carInfo, status, userEmail)

			// 线程安全地添加到结果
			channelMu.Lock()
			channels = append(channels, channel)
			channelMu.Unlock()
		}(car)
	}

	// 等待所有car状态请求完成
	localWg.Wait()

	return channels
}
